require "Common/define"
require "Logic/Config"
require "Common/functions"
require "Common/Class"

SDKManager = {}
local this = SDKManager
--SDK与Unity之前的通信状态，基本与 U8Code.class 中的枚举相同
SDKManager.SDK2Unity_CallbackStatus = {
    CODE_PAY_SUCCESS = 10,
    CODE_PAY_FAIL = 11,
    CODE_PAY_CANCEL = 33,
    CODE_PAY_UNKNOWN = 34,
}

function SDKManager.Login()
    if TAManager.IsFirstShowSDKLogin then
        TAManager.IsFirstShowSDKLogin = false
        TAManager.TrackByDictionary("first_show_sdk_login")
    end
    LoginSDK.GetInstance():LoginU8SDK()
end
function SDKManager.Logout()
    LoginSDK.GetInstance():LoginOutU8SDK()
end

function SDKManager.GetAPKName()
    if SDKManager.apkname == nil then
        if Application.platform == RuntimePlatform.Android then
            SDKManager.apkname = Util.GetApkPackageName()
        elseif Application.platform == RuntimePlatform.IPhonePlayer then
            SDKManager.apkname = "com.feiyou.fszx"
        else
            SDKManager.apkname = "com.feiyou.fszx"
        end
    end
    return SDKManager.apkname
end

--[[/// <summary>
    /// 支付
    /// </summary>
    /// <param name="productId">充值商品ID，游戏内的商品ID</param>
    /// <param name="productName">商品名称，比如100元宝，500钻石...</param>
    /// <param name="productDesc">商品描述，比如 充值100元宝，赠送20元宝</param>
    /// <param name="price">充值金额(单位：分)</param>
    /// <param name="buyNum">购买数量，一般都是1</param>
    /// <param name="coinNum">玩家当前身上剩余的游戏币</param>
    /// <param name="serverID">玩家所在服务器的ID</param>
    /// <param name="serverName">玩家所在服务器的名称</param>
    /// <param name="roleID">玩家角色ID</param>
    /// <param name="roleName">玩家角色名称</param>
    /// <param name="roleLevel">玩家角色等级</param>
    /// <param name="vip">玩家vip等级</param>
    /// <param name="payNotifyUrl">游戏服务器支付回调地址，渠道SDK支付成功，异步通知U8Server，U8Server根据该地址，通知游戏服务器发货</param>
    /// <param name="extension">支付成功之后，U8Server原样返回给游戏服务器</param>
--]]
function SDKManager.Pay(productId,productName,productDesc,price,buyNum,coinNum,serverID,serverName,roleID,roleName,roleLevel,vip,payNotifyUrl,extension)
    --local price = 1
    --local serverID = AppConst.ServerId
    --local serverName = "测试服务器"
    --local roleID = HeroManager.GetRoleId()
    --local roleName = HeroManager.GetRoleName()
    --local roleLevel = HeroManager.GetRoleLevel()
    --local vip = CostManager.getVipLevel()

    LoginSDK.GetInstance():PayU8SDK(productId, productName, productDesc, price, buyNum,
            tonumber(tostring(coinNum)), serverID, serverName, roleID, roleName,
            roleLevel, vip, payNotifyUrl, extension)
end

function SDKManager.LoginOutSuccess()
    print("收到登出回调===")
    Config.isU8sdkLoginOut = true
    logicMgr.LoginManager.SetAutoLogin(true)
    Game.ResetStart(true)
    this.IMDisconnect()
end
function SDKManager.ExitCallBackU8SDK(message)
    print("收到关闭回调了===")
    logicMgr.UIShowManager.ShowCommonConfirm("确认要离开游戏吗？","", function()
        LoginManager.QuitGame()
    end, nil, nil, "确认", "取消")
end
--function SDKManager.SwitchAccount(message)
--    print("收到u8sdk调用的切换账号回调===")
--    logicMgr.LoginManager.SetAutoLogin(false)
--    Game.ResetStart(false)
--    Game.stopHeart()
--    SDKManager.IMDisconnect()
--end
function SDKManager.SDK2Unity_CallbackHandle(status, message)
    this.logError("SDKManager.SDK2Unity_CallbackHandle,status:   "..status..",  message:    "..message)
    status = tonumber(status)

    local m_arr = string.split(message, "=")

    local order_info = costHandler.GetOrderInfo()
    local _payDic                 = {} --埋点处理
    if order_info then
        if #m_arr == 2 then
            _payDic.order_id      = m_arr[2]
        else
            _payDic.order_id      = -1
        end
        
        _payDic.productid_u8      = order_info.productid_u8
        _payDic.product_id        = order_info.productId
        _payDic.recharge_amount   = order_info.recharge_amount
        _payDic.error_code        = status
    end

    if status == SDKManager.SDK2Unity_CallbackStatus.CODE_PAY_SUCCESS then
        local first = GetPlayerPrefs("first_pay_success")
        local serverTime = HelperFunc.GetServerTime() 
        serverTime = os.date("%Y-%m-%d %H:%M:%S", serverTime)
        if first == nil then
            TAManager.UserSet("first_pay_time", serverTime)
            SetPlayerPrefs("first_pay_success", 1)
        end
        
        if order_info then
            TAManager.UserAdd("total_revenue", order_info.recharge_amount)
            costHandler.ReqPaySuccess(order_info.extension);
        end
        TAManager.UserSet("last_pay_time", serverTime)
    elseif status == SDKManager.SDK2Unity_CallbackStatus.CODE_PAY_FAIL then
        TAManager.TrackByDictionary("order_pay_fail", _payDic)
    elseif status == SDKManager.SDK2Unity_CallbackStatus.CODE_PAY_CANCEL then
        TAManager.TrackByDictionary("order_pay_fail", _payDic)
    elseif status == SDKManager.SDK2Unity_CallbackStatus.CODE_PAY_UNKNOWN then
        TAManager.TrackByDictionary("order_pay_fail", _payDic)
    end
end
---- IM 相关 Start ----------------------------------------------------------------------------
this.enableLog = false
this.isSendConnect = false
this.isConnectChat = false
this.worldRoomName = ""
this.cityRoomName = ""
this.unionRoom = ""
this.IMCallbackState = {
    ConnectSuc = 0,
    ConnectFailed = 1,
    JoinChatRoomSuc = 2,
    JoinChatRoomFailed = 3,
    QuitChatRoomSuc = 4,
    QuitChatRoomFailed = 5,
}
function SDKManager.IsWindowEditor()
    return UnityEngine.Application.platform == UnityEngine.RuntimePlatform.WindowsEditor
end
function SDKManager.ResChatServiceInfo(appKey,userToken,worldRoom,cityRoom,unionRoom,teamBossRoom)
    this.logError("[IM]ResChatServiceInfo  "..tostring(worldRoom)..","..tostring(cityRoom)..","..tostring(unionRoom)..","..tostring(teamBossRoom))
    SDKManager.ReqMyselfUserInfo()
    LoginSDK.GetInstance():CallIM_EnableLog(this.enableLog)
    LoginSDK.GetInstance():CallIM_Init(appKey)
    this.worldRoomName = worldRoom
    this.cityRoomName = cityRoom
    this.unionRoom = unionRoom
    this.teamBossRoom=teamBossRoom
    if not this.isSendConnect then
        this.isSendConnect = true
        LoginSDK.GetInstance():CallIM_Connect(userToken)
    end
end
function SDKManager.ResUnionRoomChange(unionRoom)
    local old = this.unionRoom
    this.unionRoom = unionRoom
    if not string.IsNilOrEmpty(old) then
        SDKManager.QuitChatRoom(old)
    end
    if not string.IsNilOrEmpty(unionRoom) then
        SDKManager.JoinChatRoom(unionRoom,20)
    end
end
function SDKManager.ResInvasionTeamChange(teamBossRoom)
    local old = this.teamBossRoom
    this.teamBossRoom = teamBossRoom
    if not string.IsNilOrEmpty(old) then
        SDKManager.QuitChatRoom(old)
    end
    if not string.IsNilOrEmpty(teamBossRoom) then
        SDKManager.JoinChatRoom(teamBossRoom,20)
    end
end
function SDKManager.IMCallback_Handle(message)
    this.logError("[IM]IMCallback_HandleIMCallback_Handle   "..message)
   local tb = string_split(message,",")
    if #tb < 2 then return end
    local type = tonumber(tb[1])
    if type == this.IMCallbackState.ConnectSuc then
        this.isConnectChat = true
        logicMgr.ChatManager.LoadAllMsgFromFile()
        SDKManager.TestJoinChatRoom()
    elseif type == this.IMCallbackState.JoinChatRoomSuc then
        --UISysTips.AddMsg("加入聊天室成功-"..tb[2])
        if tb[2] == this.cityRoomName then
            chatHandler.SendCityPlayerInfo()
            this.GetCityChatRoomInfo()
        end
    elseif type == this.IMCallbackState.JoinChatRoomFailed then
        --UISysTips.AddMsg("加入聊天室失败")
    elseif type == this.IMCallbackState.QuitChatRoomSuc then
    end
end
function SDKManager.IMCallback_ReceiveTextMessage(message)

    local msg = decodeJsonStrToTabel(message)
    if tostring(msg.senderUserId) == "0" or string.IsNilOrEmpty(msg.content) then
        return
    end
    this.logError("[IMc#]ReceiveTextMessage: "..message)
    local msgData = {}
    msgData.id = msg.messageId

    msgData.Message = msg.content;
    msgData.head = msg.senderPortraitUri;                 --自己的头像/modelId
    --msgData["headFrame"] = msg.headFrame;
    --msgData["level"] = msg.level;               --自己的等级
    msgData.roleId = msg.senderUserId;             --自己的id
    msgData.roleName = msg.senderUserName;         --自己的名字
    --msgData["titleId"] = msg.titleId;           --勋章id
    msgData["unRead"] = true;
    msgData.time = msg.sentTime;
    --msgData["PlayerId"] = msg.PlayerId;         --私聊对象id
    --msgData["PlayerName"] = msg.PlayerName;     --私聊对象名字
    --msgData["PlayerHead"] = msg.PlayerHead;     --私聊对象头像/modelId
    local extra = decodeJsonStrToTabel(msg.extra)
    if extra then
        msgData.headFrame = extra.headFrame
        msgData.headPic = extra.headPic
        msgData.level = extra.level
        msgData.lbs = extra.lbs
        msgData.titleId = extra.titleId
        msgData.unionName = extra.unionName
        msgData.emoji = extra.emoji
        msgData.genes = extra.genes
        msgData.serverId = extra.serverId
        msgData.weaponLevel = extra.weaponLevel
        msgData.favorLv=extra.favorLv
    end
    local type = tonumber(msg.conversationType)
    if type == EnumConst.ConversationType.PRIVATE then
        msgData.Channel =  Config.MsgChannel.Person
        if msg.senderUserId == logicMgr.HeroManager.GetRoleId() then
            if logicMgr.FriendManager.IsFriend(msg.targetId) then
                local friend = FriendManager.GetMyFriend(msg.targetId)
                msgData.PlayerId = msg.targetId;         --私聊对象id
                msgData.PlayerName = friend.name     --私聊对象名字
                msgData.PlayerHead = friend.pic
                msgData.PlayerHeadFrame = friend.picFrame
            else
                return
            end
        else
            msgData.PlayerId = logicMgr.HeroManager.GetRoleId()         --私聊对象id
            msgData.PlayerName = logicMgr.HeroManager.GetRoleName()     --私聊对象名字
            msgData.PlayerHead = HeroManager.GetRoleHeadID();     --私聊对象头像/modelId
            msgData.PlayerHeadFrame = HeroManager.GetRoleHeadFrame()
        end
    elseif type == EnumConst.ConversationType.CHATROOM then
        if msg.targetId == this.worldRoomName then
            msgData.Channel = Config.MsgChannel.World
        elseif msg.targetId == this.cityRoomName then
            msgData.Channel = Config.MsgChannel.Server
        elseif msg.targetId == this.unionRoom then
            msgData.Channel = Config.MsgChannel.Guild
        elseif msg.targetId==this.teamBossRoom then
            log("receivedInvasionMessage"..msgData.Message)
            msgData.Channel=Config.MsgChannel.InvasionTeam
        end
    end
    if chatHandler.CheckIsCityPlayerMsg(msgData) then
        return
    end
    logicMgr.ChatManager.addChatMsg(msgData)
end
function SDKManager.ReqMyselfUserInfo(myExtra)
    local userId = logicMgr.HeroManager.GetRoleId()
    local _userName = logicMgr.HeroManager.GetRoleName()
    local _portraitUrl = tostring(HeroManager.GetRoleHeadID())
    local extra = TablePool.Get()
    extra.headFrame = HeroManager.GetRoleHeadFrame()
    extra.headPic = logicMgr.HeroManager.GetRoleInfo("pic")
    extra.level = HeroManager.GetRoleLevel()
    extra.lbs = logicMgr.LBSManager.GetLocationName()
    extra.serverId = Config.chatServerId
    extra.rank = logicMgr.HeroManager.GetWeaponQuality()
    --公会名
    extra.unionName = logicMgr.GuildManager.getUnionName();
    --勋章
    local tempList = logicMgr.TitleManager.GetTitleData().showList
    extra.titleId = tempList and tempList[1] or 0
    --pet
    local _petInfo = logicMgr.PetManager.GetFollowPetInfo()
    if _petInfo then
        extra.genes = {};
        for k,v in pairs(_petInfo.genes) do
        extra.genes[k] = v
        end
    end
    local headHeroData=logicMgr.HeroManager.getHeroDatabyModelId(logicMgr.HeroManager.GetRoleHeadID(),true) or {}
    extra.favorLv=headHeroData.favorLv or 0
    --专武
    extra.weaponLevel = logicMgr.EquipManager.getWeaponLevelByModelId(HeroManager.GetRoleHeadID())
    if myExtra then
        for k,v in pairs(myExtra) do
            extra[k] = v
        end
    end
    local _extra = getJsonStr(extra)
    TablePool.Release(extra)
    LoginSDK.GetInstance():CallIM_SetMyselfUserInfo(userId,_userName,_portraitUrl,_extra)
end
function SDKManager.IMCallback_ConnectFailed(errorCode)
    errorCode = tonumber(errorCode)
    this.logError("[IMCallback_ConnectFailed] "..errorCode)
end
function SDKManager.IMCallback_GetChatRoomInfo(json)
    this.logError("[IMC#]IMCallback_GetChatRoomInfo :"..json)
    chatHandler.GetChatRoomInfo(json)
end

function SDKManager.JoinChatRoom(chatRoomId,defMessageCount)
    this.logError("SDKManager.JoinChatRoom"..chatRoomId)
    LoginSDK.GetInstance():CallIM_JoinChatRoom(chatRoomId,defMessageCount)
end

function SDKManager.QuitChatRoom(chatRoomId)
    LoginSDK.GetInstance():CallIM_QuitChatRoom(chatRoomId)
end
function SDKManager.IMDisconnect()
    this.isSendConnect = false
    print("IMDisconnect")
    LoginSDK.GetInstance():CallIM_Disconnect(false)
end
function SDKManager.SendTextMessageByCity(content)
    local _conversationType =  LoginSDK.ConversationType.CHATROOM
    LoginSDK.GetInstance():CallIM_SendTextMessage(content, this.cityRoomName, _conversationType)
end
function SDKManager.SendTextMessageByPrivate(content, playerId)
    this.logError("SendTextMessageByPrivate========== "..content..","..playerId)
    local targetId = playerId
    local _conversationType =  LoginSDK.ConversationType.PRIVATE
    LoginSDK.GetInstance():CallIM_SendTextMessage(content, targetId, _conversationType)
end
function SDKManager.SendTextMessageByWorld(content)
    local _conversationType = LoginSDK.ConversationType.CHATROOM
    MyLog("世界频道发送："..content)
    LoginSDK.GetInstance():CallIM_SendTextMessage(content, this.worldRoomName, _conversationType)
end
function SDKManager.SendTextMessageByGuild(content)
    local _conversationType = LoginSDK.ConversationType.CHATROOM
    LoginSDK.GetInstance():CallIM_SendTextMessage(content, this.unionRoom, _conversationType)
end
function SDKManager.SendTextMessageByInvasion(content)
    MyLog("SendInvasion"..content,"this.teamBossRoom"..this.teamBossRoom)
    local _conversationType = LoginSDK.ConversationType.CHATROOM
    LoginSDK.GetInstance():CallIM_SendTextMessage(content, this.teamBossRoom, _conversationType)
end
function SDKManager.CallIM_EnableLog(enable)
    LoginSDK.GetInstance():CallIM_EnableLog(enable)
end
function SDKManager.GetCityChatRoomInfo()
    this.logError("[IMC#]GetCityChatRoomInfo")
    LoginSDK.GetInstance():CallIM_GetChatRoomInfo(this.cityRoomName,20)
end
function SDKManager.logError(str)
    if this.enableLog then
        logError(str)
    end
end

-- iOS Widget跳转接口（临时放在此处）
---@param id number 页面id
function SDKManager.WidgetToView(id)
    print(">>>>>>>>>>>>>>>>WidgetToView: ", id)
end

--TODO 测试
function SDKManager.TestJoinChatRoom()
    --加入世界
    SDKManager.JoinChatRoom(this.worldRoomName,20)
    --加入主城
    SDKManager.JoinChatRoom(this.cityRoomName,20)
    --加入公会
    if not string.IsNilOrEmpty(this.unionRoom) then
        SDKManager.JoinChatRoom(this.unionRoom,20)
    end
end

--客服中心未读消息
function SDKManager.AccountCenterRedPoint(count)
    --FireEvent(Config.EventType.Account_center_unread_count, count)
end

function SDKManager.GetAccountCenterCount()
    if CompareOriginVersion("1.4.2.0001") then
        return LoginSDK.GetInstance():GetAccountCenterRedCount() or 0
    end
    
    return 0--LoginSDK.GetInstance():GetAccountCenterRedCount() or 0
end

---- IM 相关 End ------------------------------------------------------------------------------
return SDKManager